% read in an EDI file and compute MT app. rs. and phs.
% provision to calculate e-pre coherency 30.7.2002
% uses cohe.m for obtaining coherencey
% latest date 12.10.2002


function[SPM,er]=edi_in(fid),

er = 0;


%-------- read in contents -----------------------------

flag = 1;
while flag == 1,
  % [A,count] = fscanf(fid,'%[^\n]s',1);
  A = fgets(fid);
  A(A==' ')=[];
  if findstr(A,'LAT') == 1,
    flag = 0;
   end;
end;
 A1 = fgets(fid);  
 A1(A1==' ')=[];
SPM.head.Lat = str2num(setstr(A(5:8)))+str2num(setstr(A(10:11)))/60 + str2num(setstr(A(13:14)))/3600;
SPM.head.Log = str2num(setstr(A1(6:9)))+str2num(setstr(A1(11:12)))/60 + str2num(setstr(A1(14:15)))/3600;

flag = 1;
K = 0;
while flag == 1,
[A,count] = fscanf(fid,'%s',1);
if strcmp(A,'>=SPECTRASECT') == 1,
flag = 0;
end;
K = K + 1;
 if K > 5000,
	fprintf('Error in file\n');
	return;
 end;
end;

[siteID,count] = fscanf(fid,'%s',1);
SPM.head.site = siteID;
[Nchannel,count] = fscanf(fid,'%s',1);
[Nfrq,count] = fscanf(fid,'%s',1);
[Nblocks,count] = fscanf(fid,'%s',2);

nfrq = str2num(Nfrq(7:length(Nfrq)));
nchan =str2num(Nchannel(7:length(Nchannel)));
[ChannelID,count] = fscanf(fid,'%f',[1 nchan]);

[head,count] = fscanf(fid,'%c',[2 1]);
for i = 1:nfrq,
   if i>1,
      [head,count] = fscanf(fid,'%c',[4 1]);
   end;
   %   [head,count] = fscanf(fid,'%c',[72 1]);
   
   sflag = 0;
   s = 1;
   while sflag == 0,
   str(s) = fscanf(fid,'%c',[1 1]);
   if str(s) == '/',
      str(s+1:s+3) = fscanf(fid,'%c',[3 1]);
      sflag = 1;
   end;
      s = s+1;
   end;

   [data,count] = fscanf(fid,'%f',[nchan nchan]);
   frq(i) = str2num(setstr(str(19:27)));
   SPM.spectra(i).data(:,:) = data';
   SPM.spectra(i).freq = frq(i);
   SPM.spectra(i).dof.avgf = 1;
   pp = str2num(setstr(str(63:66)));
   if length(pp) < 1,
      pp = 5;
   end;
   SPM.spectra(i).dof.avgt = pp;
end;
SPM.head.frq=frq;
fclose(fid);
